//
//  HJChatMessageVideoCell.m
//  XWC
//
//  Created by Hello on 2022/10/25.
//

#import "HJChatMessageVideoCell.h"
#import "HJChatMessageVideoLayout.h"
#import "HJChatMessageModel.h"
#import "HJVideoCoverDownloader.h"
#import "HJProgressMarkView.h"

@interface HJChatMessageVideoCell()

@property (nonatomic, strong) UIImageView *playImageView;
@property (nonatomic, weak) HJProgressMarkView *progressMarkView;
@property (nonatomic, weak) UIView *infoView;
@property (nonatomic, weak) UIView *progressView;
@property (nonatomic, weak) UILabel *durationLabel;
@property (nonatomic, weak) UIImageView *iconImageView;

@end


@implementation HJChatMessageVideoCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        
        self.bubbleView.clipsToBounds = YES;
        
        UIImageView *imageView = [UIImageView addToView:self.bubbleView];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.backgroundColor = UIColorMake(0xececec);
        _contentImageView = imageView;
        
        UIImageView *playImageView = [UIImageView addToView:imageView];
        playImageView.image = [UIImage imageNamed:@"cell_video_icon"];
        playImageView.contentMode = UIViewContentModeScaleAspectFill;
        _playImageView = playImageView;
        
        _progressMarkView = [HJProgressMarkView addToView:self.bubbleView];
        _progressMarkView.progress = 0;
        _progressMarkView.hidden = YES;
        _progressMarkView.layer.masksToBounds = YES;
        
        UIView *infoView = [UIView addToView:self.bubbleView];
        infoView.addCornerRadius(5);
        infoView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.5];
        _infoView = infoView;
        [infoView addTapGesturesWithTarget:self action:@selector(tapInfoView:)];
        
        UIView *progressView = [UIView addToView:infoView];
        progressView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.5];
        _progressView = progressView;
        
        UILabel *durationLabel = [UILabel addToView:infoView];
        durationLabel.font = UIFontMake(12);
        durationLabel.textColor = UIColor.whiteColor;
        _durationLabel = durationLabel;
        
        UIImageView *iconImageView = [UIImageView addToView:infoView];
        iconImageView.contentMode = UIViewContentModeScaleAspectFill;
        _iconImageView = iconImageView;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateChatFileUploadProgressNotification:) name:updateChatFileUploadProgressNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDownloadStateChangeNotification:) name:downloadStateChangeNotification object:nil];
        
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    
    HJChatMessageVideoLayout *videoLayout = (HJChatMessageVideoLayout *)self.messageLayout;
    
    _contentImageView.frame = CGRectMake(0, 0, self.messageLayout.containerViewRect.size.width, self.messageLayout.containerViewRect.size.height);
    _playImageView.frame = CGRectMake((_contentImageView.tj_width - 40) * 0.5, (_contentImageView.tj_height - 40) * 0.5, 40, 40);
    _progressMarkView.frame = videoLayout.progressMarkRect;
    _infoView.frame = videoLayout.infoRect;
    _iconImageView.frame = videoLayout.iconRect;
    _durationLabel.frame = videoLayout.textRect;
}

- (void)setMessageLayout:(HJChatMessageLayout *)messageLayout {
    [super setMessageLayout:messageLayout];
    
    HJChatMessageVideoLayout *videoLayout = (HJChatMessageVideoLayout *)self.messageLayout;
    
    if (messageLayout.isSelfSend) {
        [self updateProgress:messageLayout.messageModel.progress];
    } else {
        [self updateDownloadProgress:messageLayout.messageModel.progress];
    }
    
    if (TJIM_isSelf(messageLayout.messageModel.senderId) && [[NSFileManager defaultManager] fileExistsAtPath:messageLayout.messageModel.thumbnailPath]) {
        _contentImageView.image = [UIImage imageWithContentsOfFile:messageLayout.messageModel.thumbnailPath];
    } else if (!isEmptyString(messageLayout.messageModel.thumbnailUrl)) {
        [_contentImageView tj_setImageWithUrl:messageLayout.messageModel.thumbnailUrl];
    } else {
        _contentImageView.image = nil;
        [HJVideoCoverDownloader.shareDownLoader downloadWithUrl:messageLayout.messageModel.fileUrl completion:^(UIImage * _Nullable thumbnail) {
            self.contentImageView.image = thumbnail;
        }];
    }
    
    HJTaskState state = [videoLayout.messageModel.extension intValue];
    if (state == HJTaskStateOngoing) {//下载中
        self.iconImageView.image = [UIImage imageNamed:@"video_cancel"];
    } else if (state == HJTaskStateError) {//下载失败
        self.iconImageView.image = [UIImage imageNamed:@"video_downloadingError"];
    } else if (state == HJTaskStateCancel || state == HJTaskStateNone) {
        self.iconImageView.image = [UIImage imageNamed:@"video_downloading"];
    }
    
    self.durationLabel.text = videoLayout.text;
}

- (void)updateDownloadProgress:(CGFloat)progress {
    self.messageLayout.messageModel.progress = progress;
    NSInteger state = [self.messageLayout.messageModel.extension intValue];
    if (state == HJTaskStateSucceed) {
        self.progressView.frame = CGRectZero;
    } else {
        self.progressView.frame = CGRectMake(0, 0, progress * self.infoView.tj_width, self.infoView.tj_height);
    }
}

- (void)updateProgress:(CGFloat)progress {
    
    self.progressMarkView.progress = progress;
    self.messageLayout.messageModel.progress = progress;
    if (self.messageLayout.messageModel.msgStatus == HJMessageStatusSending) {
        [self.progressMarkView startAnimating];
        self.playImageView.hidden = YES;
    }  else {
        [self.progressMarkView stopAnimating];
        self.playImageView.hidden = NO;
    }
}

- (void)tapInfoView:(UITapGestureRecognizer *)tap {
    if ([self.delegate respondsToSelector:@selector(chatMessageDidClickVideoInfoViewCell:)]) {
        [self.delegate chatMessageDidClickVideoInfoViewCell:self];
    }
}

- (void)handleUpdateChatFileUploadProgressNotification:(NSNotification *)not {
    NSDictionary *info = not.object;
    
    NSString *msgId = info[@"msgId"];
    CGFloat progress = [info[@"progress"] floatValue];
    if (![msgId isEqualToString:self.messageLayout.messageModel.msgId]) return;
    [self updateProgress:progress];
}

- (void)handleDownloadStateChangeNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    
    NSString *msgId = messageModel.msgId;

    if (![msgId isEqualToString:self.messageLayout.messageModel.msgId]) return;
    
    self.messageLayout.messageModel.extension = messageModel.extension;

    HJTaskState state = messageModel.extension.intValue;

    if (state == HJTaskStateOngoing) {
        
        HJChatMessageVideoLayout *videoLayout = (HJChatMessageVideoLayout *)self.messageLayout;
        [videoLayout layoutInfoView];
        [self setNeedsLayout];
        [self layoutIfNeeded];

        HJTaskState state = [videoLayout.messageModel.extension intValue];
        if (state == HJTaskStateOngoing) {//下载中
            self.iconImageView.image = [UIImage imageNamed:@"video_cancel"];
        } else if (state == HJTaskStateError) {//下载失败
            self.iconImageView.image = [UIImage imageNamed:@"video_downloadingError"];
        } else if (state == HJTaskStateCancel || state == HJTaskStateNone) {
            self.iconImageView.image = [UIImage imageNamed:@"video_downloading"];
        }
        self.durationLabel.text = videoLayout.text;
        [self updateDownloadProgress:messageModel.progress];
        
    } else if (state == HJTaskStateSucceed) {
        
        self.messageLayout.messageModel.localPath = messageModel.localPath;
        
        self.progressView.frame = CGRectZero;
        HJChatMessageVideoLayout *videoLayout = (HJChatMessageVideoLayout *)self.messageLayout;
        [videoLayout layoutInfoView];
        [self setNeedsLayout];
        [self layoutIfNeeded];
        self.messageLayout = videoLayout;
        
    } else {
                
        self.progressView.frame = CGRectMake(0, 0, messageModel.progress * self.infoView.tj_width, self.infoView.tj_height);
        HJChatMessageVideoLayout *videoLayout = (HJChatMessageVideoLayout *)self.messageLayout;
        [videoLayout layoutInfoView];
        [self setNeedsLayout];
        [self layoutIfNeeded];
        self.messageLayout = videoLayout;
    }

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
